package com.manong.bookstore.user.controller;

import com.manong.common.utils.R;
import com.manong.bookstore.user.session.UserSession;
import com.manong.bookstore.user.session.UserSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("user/session")
public class UserSessionController {
	@Autowired
	UserSessionManager userSessionManager;

	/**
	 * 测试用，检查所有session，不更新最后访问时间
	 */
	@RequestMapping("/list")
	public R list() {
		return R.ok().put("userSessions", userSessionManager.getUserSessions());
	}

	/**
	 * 测试用，清除所有session
	 */
	@RequestMapping("/clear")
	public R clear() {
		userSessionManager.getUserSessions().clear();
		return R.ok();
	}

	/**
	 * 新建session，返回sessionId
	 */
	@RequestMapping("/create")
	public String create() {
		return userSessionManager.addUserSession();
	}

	/**
	 * 删除session
	 */
	@RequestMapping("/remove")
	public boolean remove(@RequestParam String sessionId) {
		return userSessionManager.delUserSession(sessionId);
	}

	/**
	 * 添加属性到指定session
	 */
	@RequestMapping("/setAttribute")
	public boolean setAttribute(@RequestParam String sessionId,@RequestParam String key,@RequestParam String value) {
		UserSession userSession = userSessionManager.getUserSession(sessionId);

		if(userSession == null)
			return false;

		userSession.setAttribute(key, value);

		return true;
	}

	/**
	 * 查询是否存在指定id的session
	 */
	@RequestMapping("/search")
	public boolean search(@RequestParam String sessionId) {
//		System.out.println(sessionId);

		return userSessionManager.exist(sessionId);
	}

	/**
	 * 获取session的全部属性
	 */
	@RequestMapping("/info")
	public R info(@RequestParam String sessionId) {
//		System.out.println(userSessionManager.getUserSession(sessionId));
		UserSession userSession = userSessionManager.getUserSession(sessionId);

		return R.ok().put("session", userSession);
	}
}
